if (!Detector.webgl) Detector.addGetWebGLMessage();

let camera, scene, renderer, controls;

init();

function  getQueryVariable(name) {
  const reg = new RegExp("(^|&)" + name+ "=([^&]*)(&|$)", "i");
  const result = window.location.search.substr(1).match(reg);
  if ( result != null ){
     return decodeURI(result[2]);
 }else{
     return null;
 }
}

function init() {

  scene = new THREE.Scene();
  scene.add(new THREE.AmbientLight(0x999999));

  camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 500);
  camera.up.set(0, 0, 1);
  camera.position.set(0, -9, 6);

  camera.add(new THREE.PointLight(0xffffff, 0.8));

  scene.add(camera);

  let grid = new THREE.GridHelper(25, 50, 0xffffff, 0x555555);
  grid.rotateOnAxis(new THREE.Vector3(1, 0, 0), 90 * (Math.PI / 180));
  scene.add(grid);

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setClearColor(0x999999);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  let loader = new THREE.STLLoader();

  // 获取链接中的stl路径
  let stlAddress = getQueryVariable('stl')
  let material = new THREE.MeshPhongMaterial({ color: 0x0e2045, specular: 0x111111, shininess: 200 });
  loader.load('http://' + window.base_url + '/models/' + stlAddress, function (geometry) {
    let mesh = new THREE.Mesh(geometry, material);

    mesh.position.set(0, 0, 0);
    mesh.rotation.set(0, 0, 0);
    mesh.scale.set(.02, .02, .02);

    mesh.castShadow = true;
    mesh.receiveShadow = true;
    $.ajax({
      url: "/express_backend", success: function (res) {
        // console.log(res, $('#area'))
        $('#area').text(res.data.area)
        $('#weight').text(res.data.weight)
        $('#volume').text(res.data.volume)
      }
    });
    scene.add(mesh);

    render();
  });

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.addEventListener('change', render);
  window.addEventListener('resize', onWindowResize, false);

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);

  render();

}
function uploadAttachment(e) {
  $("#form").ajaxSubmit(function (res) {
    // 对于表单提交成功后处理，message为提交页面saveReport.htm的返回内容
    // console.log(res)
    $('#area').text(res.data.area)
    $('#weight').text(res.data.weight)
    $('#volume').text(res.data.volume)
    $('#url').text(res.data.url)
  });
  return false
}
function render() {
  // controls.update();
  renderer.render(scene, camera);

}
